package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hotMoney/data"
	"hotMoney/model"
	b "hotMoney/service/filterluaInit"
	a "hotMoney/service/redisluainit"
	"net/http"
	"strconv"
)

//未消费的积分队列
const key3 = "NRewardList"
//已消费的积分队列
const key4 = "YRewardList"
//去重的hash
const key1 = "hasUser"

func GetRewardInfo(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"msg":"1111",
	})
}

func RewardMoney(c *gin.Context) {
	//获取数据
	username := c.PostForm("username")
	password := c.PostForm("password")
	usr := model.User{
		Username: username,
		Password: password,
	}
	//用户名不能为空
	if username == "" {
		c.JSON(http.StatusOK, gin.H{
			"message":"用户名不能为空！",
		})
		return
	}
	//抢积分先进行限流filter处理
	if b.GetFilterBucket(){
		//filter通过再执行原子操作
		res := a.CacheGetReward(key1, username, key3, key4)
		if res == 0 {
			c.JSON(http.StatusOK, gin.H {
				"message":"用户已经抢过积分",
			})
			return
		}
		if res == -1 {
			c.JSON(http.StatusOK, gin.H {
				"message":"积分已经抢完",
			})
			return
		}
		if res == -2 {
			c.JSON(http.StatusOK, gin.H {
				"message":"预料之外的错误，请检查程序!",
			})
			return
		}
		//已抢到积分的话，根据红包id去查询积分金额返回
		amount, _:= data.GetAmount(strconv.Itoa(res))
		m, _ := strconv.Atoi(amount)
		usr.Amount = m
		//更新user表
		Userchan <- usr
		c.JSON(http.StatusOK, gin.H{
			"message":"成功领取积分",
			"amount":amount,
		})
	}else {
		fmt.Println("没有令牌了！！！")
		return
	}

}